package test5.lupeng.jf.com.teamdemo.activitys;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.adapter.UserListAdapter;
import test5.lupeng.jf.com.teamdemo.bean.AtOthersBean;
import test5.lupeng.jf.com.teamdemo.bean.request.UserListBean;
import test5.lupeng.jf.com.teamdemo.bean.response.UserListResponse;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;

public class UserListActivity extends AppCompatActivity {
    private static final String TAG = "UserListActivity";
    ArrayList<UserListResponse.ResultBean> mResultBeen  =new ArrayList<>();
    ArrayList<AtOthersBean> atOthersBeen =new ArrayList<>();
    String userId;
    private UserListAdapter mAdapter;
    private RecyclerView rl_userlist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
        SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
        userId = sp.getString("objectId", null);
        initView();
    }


    /**
     * 初始化视图
     */
    private  void initView(){
        ImageView iv_back= (ImageView) findViewById(R.id.iv_back);

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        TextView tv_commit= (TextView) findViewById(R.id.tv_commit);
        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                int size=atOthersBeen.size();
                intent.putParcelableArrayListExtra("userlist",atOthersBeen);
                setResult(RESULT_OK,intent);
                finish();
            }
        });

        final EditText edit_search= (EditText) findViewById(R.id.edit_search);
        Button bt_search= (Button) findViewById(R.id.bt_search);
           bt_search.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               String username=  edit_search.getText().toString();
               if(userId==null||"".equals(userId)){
                   Toast.makeText(UserListActivity.this, "用户id为空，请登录！", Toast.LENGTH_SHORT).show();
                   return;
               }
               if(username==null||"".equals(username)){
                   Toast.makeText(UserListActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
                   return;
           }
               getUserList(userId,0,0,username);
       }});

        final HorizontalScrollView HorizontalScrollView= (android.widget.HorizontalScrollView) findViewById(R.id.HorizontalScrollView);
        HorizontalScrollView.setVisibility(View.GONE);

        final LinearLayout ll_headImage= (LinearLayout) findViewById(R.id.ll_headimage);
        ll_headImage.setVisibility(View.GONE);


        rl_userlist = (RecyclerView) findViewById(R.id.rl_userlist);
        rl_userlist.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new UserListAdapter(mResultBeen);
        rl_userlist.setAdapter(mAdapter);
        rl_userlist.setVisibility(View.GONE);

        mAdapter.setChooseListener(new UserListAdapter.ChooseListener() {
            @Override
            public void setChoose(UserListResponse.ResultBean bean) {
                HorizontalScrollView.setVisibility(View.VISIBLE);
                ll_headImage.setVisibility(View.VISIBLE);
                ImageView imageView  =new ImageView(UserListActivity.this);
                Glide.with(UserListActivity.this).load(bean.getHeadProtrait())
                        .asBitmap().into(imageView);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(80,
                        80);
                imageView.setLayoutParams(params);
                ll_headImage.addView(imageView);
                atOthersBeen.add(new AtOthersBean(bean.getUserId(),bean.getUsername()));
            }
        });

    }


    /**
     * 获取搜索用户结果
     * @param userId            当前用户id
     * @param limit             请求个数
     * @param timestamp         时间戳
     * @param otherUserName     其他用户用户名
     */
    private  void getUserList(String userId,int limit,int timestamp,String otherUserName){
         String url ="https://leancloud.cn:443/1.1/functions/getUserList";
        OkHttpClient client  = new OkHttpClient();
        UserListBean bean = new UserListBean(userId,limit,timestamp,otherUserName);
        Request request = HTTPUtils.requestPost(bean,url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                   String jsonResult  = response.body().string();

                  Log.e(TAG, "onResponse: "+jsonResult );
                 if(response.code()==200){
                     UserListResponse userListResponse = new Gson().fromJson(jsonResult,UserListResponse.class);
                     mResultBeen.clear();
                     mResultBeen.addAll(userListResponse.getResult());
                   runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                            rl_userlist.setVisibility(View.VISIBLE);
                            mAdapter.notifyDataSetChanged();
                       }
                   });
                }
            }
        });

    }
}
